import axios from 'axios';
import { setToken, setRefreshToken, getToken } from './token';
import { refreshToken, isRefreshToken } from './refreshToken';

const ins = axios.create({
    baseURL: 'http://localhost:9527',
    headers: {
        Authorization: `Bearer ${getToken()}`,
    },
});

ins.interceptors.response.use( async (res) => {
    // 缓存 token
    if(res.headers.authorization) {
        const token = res.headers.authorization.replace('Bearer ', '')
        setToken(token)
        // 指定默认配置设置头文件
        ins.defaults.headers.Authorization = `Bearer ${token}`
    }
    // 缓存 refreshtoken
    if(res.headers.refreshtoken) {
        const refreshToken = res.headers.refreshtoken.replace('Bearer ', '')
        setRefreshToken(refreshToken)
    }
    // 缺少需要验证的身份信息token
    if(res.data.code === 401 && !isRefreshToken(res.config)) {
        const isSuccess = await refreshToken()
        if(isSuccess) {
            res.config.headers.Authorization = `Bearer ${getToken()}`
            const resp = await ins.request(res.config)
            // console.log('resp', resp)
            return resp
        }else {
            console.log('跳转到登录页')
            return res.data
        }
    }
    return res.data
})

export default ins

